package com.starbaba.spread.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.spread.model.AdvertisingDailyOB;
import com.starbaba.spread.model.AdvertisingModel;
import com.starbaba.spread.model.AdvertisingOB;
import com.starbaba.spread.model.AdvertisingVO;
import com.starbaba.spread.model.SpreadAdvertisingAdd;
import com.starbaba.spread.model.StatNginxPromote;
import com.starbaba.spread.service.AdvertisingService;
import com.starbaba.system.user.model.UserVO;

@SuppressWarnings("unchecked")
@Component(value = "advertisingServiceImpl")
public class AdvertisingServiceImpl implements AdvertisingService {

	// 声明 tt2数据源
	static BaseDao basedao = new BaseDao(Constant.POOL_PUSH_RW);

	/**
	 * 条件查询 spread_advertising
	 * 
	 * 根据表单模型AdvertisingModel<br/>
	 * 查询表数据 AdvertisingVO<br/>
	 * 映射到输出模型AdvertisingOB<br/>
	 * 
	 */

	SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
	StringBuffer sf;

	@Override
	public java.util.List<AdvertisingOB> List(int iDisplayStart, int iDisplayLength, AdvertisingModel model,
			PageResponse pageResponse) {
		sf = new StringBuffer();
		sf.append("from AdvertisingVO");
		String name = model.getName();
		String startTimeStr = model.getStartTime();
		String endTimeStr = model.getEndTime();
		UserVO userVO = (UserVO) Struts2Utils.getSessionAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
		// 过滤非管理员账户
		if (userVO.getIsManager()) {
			sf.append(" where 1=1");
		} else {
			sf.append(" where userid = '" + userVO.getUserid() + "'");
		}
		if (!StringUtils.isEmpty(name)) {
			sf.append(" and name like '%" + name + "%'");
		}
		if (!StringUtils.isEmpty(startTimeStr)) {
			sf.append(" and date >='" + startTimeStr + "'");

		}
		if (!StringUtils.isEmpty(endTimeStr)) {
			sf.append(" and date <='" + endTimeStr + "'");
		}
		sf.append(" order by date ");
		String hql = sf.toString();
		String countHql = "select count(*) " + hql;
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(AdvertisingVO.class);
		Query query = dao.getSession().createQuery(hql);
		if (iDisplayLength != 0) {
			query.setFirstResult(iDisplayStart);
			query.setMaxResults(iDisplayLength);
		}
		List<AdvertisingVO> list = query.list();
		List<AdvertisingOB> returnList = new ArrayList<AdvertisingOB>();
		AdvertisingOB itemVo;
		for (AdvertisingVO vo : list) {
			itemVo = new AdvertisingOB();
			if (null != vo.getDate()) {
				String date = dateformat.format(vo.getDate());
				itemVo.setDate(date);
			}
			itemVo.setId(vo.getId());
			itemVo.setName(vo.getName());
			itemVo.setUnitPrice(vo.getUnitPrice());
			itemVo.setUserid(vo.getUserid());
			itemVo.setTotal(vo.getTotal());
			itemVo.setStatus(1);
			itemVo.setUrl(vo.getUrl());
			try {
				if (vo.getUrl().length() < 5) {
					itemVo.setBalance(vo.getTotal());
					itemVo.setPV("0");
					itemVo.setUV("0");
					returnList.add(itemVo);
					continue;
				}
			} catch (NullPointerException e) {
				System.err.println("空  url" + vo.toString());
				itemVo.setBalance(vo.getTotal());
				itemVo.setPV("0");
				itemVo.setUV("0");
				returnList.add(itemVo);
				continue;
			}

			String[] urls = vo.getUrl().split(";");
			StringBuffer sqlurl = new StringBuffer();
			for (int i = 0; i < urls.length; i++) {
				if (urls[i].length() > 5) {
					if (i == 0) {
						sqlurl.append("and (");
					}
					if (i == urls.length - 1) {
						sqlurl.append("url like 'GET " + urls[i] + "%' or url like 'POST " + urls[i] + "%')");
					} else {
						sqlurl.append("url like 'GET " + urls[i] + "%' or url like 'POST " + urls[i] + "%' or ");
					}
				}
			}
			int total_pv = 0, total_uv = 0, addmoney = 0;
			String sqlSPV = "select SUM(PV) from stat_nginx_promote where 1=1 " + sqlurl.toString();
			String sqlSUV = "select SUM(UV) from stat_nginx_promote where 1=1 " + sqlurl.toString();
			String sqlAddMoney = "select SUM(add_money) from spread_advertising_add where ad_id='" + vo.getId() + "'";
			if (!StringUtils.isEmpty(startTimeStr)) {
				sqlSPV += " and time >='" + startTimeStr + "'";
				sqlSUV += " and time >='" + startTimeStr + "'";
			}
			if (!StringUtils.isEmpty(endTimeStr)) {
				sqlSPV += " and time <='" + endTimeStr + "'";
				sqlSUV += " and time <='" + endTimeStr + "'";
				sqlAddMoney += " and createTime <'" + endTimeStr + "'";
			}
			if (!StringUtils.isEmpty(dateformat.format(vo.getDate()))) {
				sqlSPV += " and time >='" + dateformat.format(vo.getDate()) + "'";
				sqlSUV += " and time >='" + dateformat.format(vo.getDate()) + "'";
				sqlAddMoney += " and createTime >='" + dateformat.format(vo.getDate()) + "'";
			}
			try {
				addmoney = new BaseDao(Constant.POOL_PUSH_RW).getInt(sqlAddMoney, new ArrayList<>());
				total_pv = basedao.getInt(sqlSPV, new ArrayList<>());
				total_uv = basedao.getInt(sqlSUV, new ArrayList<>());
			} catch (AppException e) {
				e.printStackTrace();
			}
			itemVo.setBalance(vo.getBalance() + addmoney - (total_pv) * vo.getUnitPrice());
			itemVo.setPV(total_pv + "");
			itemVo.setUV(total_uv + "");
			returnList.add(itemVo);

		}
		pageResponse.setITotalRecords(returnList.size());
		pageResponse.setITotalDisplayRecords(returnList.size());
		return returnList;
	}

	/**
	 * 修改广告商 spread_advertising
	 * 
	 */
	@Override
	public int update(AdvertisingModel model) {
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(AdvertisingVO.class);
		AdvertisingVO entity = new AdvertisingVO();

		try {
			entity.setDate(dateformat.parse(model.getDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (model.getDate() == null || model.getDate().length() == 0) {
			entity.setDate(new Date());
		} else {
			try {
				entity.setDate(dateformat.parse(model.getDate()));
			} catch (ParseException e) {
				System.err.println("日期" + model.getDate() + "解析异常" + e);
				e.printStackTrace();
			}
		}

		entity.setBalance(model.getBalance());
		entity.setName(model.getName());
		entity.setTotal(model.getTotal());
		entity.setUnitPrice(model.getUnitPrice());
		entity.setUrl(model.getUrl());
		entity.setUserid(model.getUserid());
		entity.setId(Long.parseLong(model.getId()));

		// 增加金额
		if (model.getAddmoney() > 0) {
			try {
				dao.save(new SpreadAdvertisingAdd(Long.parseLong(model.getId()), model.getAddmoney(), dateformat
						.parse(dateformat.format(new Date()))));
			} catch (NumberFormatException e) {
				System.err.println("日期" + model.getDate() + "格式化异常" + e);
				e.printStackTrace();
			} catch (ParseException e) {
				System.err.println("日期" + model.getDate() + "解析异常" + e);
				e.printStackTrace();
			}
		}

		Object object = dao.saveOrUpdate(entity);
		if (object == null) {
			return 0;
		} else {
			return 1;
		}

	}

	/**
	 * 查询pv uv 算出余额
	 * 
	 */
	@Override
	public java.util.List<AdvertisingDailyOB> adlist(Integer iDisplayStart, Integer iDisplayLength,
			AdvertisingModel model, PageResponse pageResponse) {
		String hql = sf.toString();
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(AdvertisingVO.class);
		Query query = dao.getSession().createQuery(
				"from AdvertisingVO where id=" + model.getId() + " order by date desc");
		if (iDisplayLength != 0) {
			query.setFirstResult(iDisplayStart);
			query.setMaxResults(iDisplayLength);
		}
		AdvertisingVO vo = (AdvertisingVO) query.list().get(0);
		List<StatNginxPromote> list;
		List<AdvertisingDailyOB> returnList = new ArrayList<AdvertisingDailyOB>();
		AdvertisingDailyOB ob;
		int pv = 0, last_pv = 0;
		double last;
		String[] urls = vo.getUrl().split(";");
		StringBuffer sf = new StringBuffer();
		boolean b = true;
		for (int i = 0; i < urls.length; i++) {
			if (urls[i].length() > 5) {
				b = false;
				if (i == 0) {
					sf.append("and (");
				}
				if (i == urls.length - 1) {
					sf.append("url like 'GET " + urls[i] + "%' or url like 'POST " + urls[i] + "%')");
				} else {
					sf.append("url like 'GET " + urls[i] + "%' or url like 'POST " + urls[i] + "%' or ");
				}
			}
		}
		String sql2 = "select pv,uv,time,url from stat_nginx_promote where time >='" + dateformat.format(vo.getDate())
				+ "' ";
		String startTimeStr = model.getStartTime();
		String endTimeStr = model.getEndTime();
		if (!StringUtils.isEmpty(startTimeStr)) {
			sql2 += " and time >='" + startTimeStr + "'";
		}
		if (!StringUtils.isEmpty(endTimeStr)) {
			sql2 += " and time <='" + endTimeStr + "'";
		}

		if (b) {// 用户没有url
			pageResponse.setITotalRecords(0);
			pageResponse.setITotalDisplayRecords(0);
			return returnList;
		}
		sql2 += sf.toString() + " order by time ";
		try {
			// 查询 pv uv 时间
			list = (List<StatNginxPromote>) basedao.list(sql2, StatNginxPromote.class, new ArrayList<>());
			String time = list.get(0).getTime();
			try {
				if (vo.getDate().getTime() < dateformat.parse(time).getTime()) {
					String sqlSPV = "select SUM(PV) from stat_nginx_promote where " + " (time >= '"
							+ dateformat.format(vo.getDate()) + "' and time< '" + time + "') " + sf.toString();
					// 查询 pv和
					last_pv = basedao.getInt(sqlSPV, new ArrayList<>());
				}
			} catch (ParseException e) {
				System.err.println("日期" + time + "解析异常" + e);
				e.printStackTrace();
			}

			for (StatNginxPromote ad : list) {
				ob = new AdvertisingDailyOB();
				last = 0;
				String sqlAddMoney = " from SpreadAdvertisingAdd  where ad_id='" + vo.getId() + "'";
				Query query2 = DAOFactory.getInstance().createHibernateDAO(SpreadAdvertisingAdd.class).getSession()
						.createQuery(sqlAddMoney);
				List<SpreadAdvertisingAdd> list2 = query2.list();
				for (SpreadAdvertisingAdd sAdd : list2) {
					try {
						if (sAdd.getCreateTime().getTime() == dateformat.parse(ad.getTime()).getTime()) {
							ob.setAddMoney(sAdd.getAddMoney() + "");
							last += sAdd.getAddMoney();
						} else if (sAdd.getCreateTime().getTime() < dateformat.parse(ad.getTime()).getTime()) {
							last += sAdd.getAddMoney();
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				pv += ad.getPv();
				ob.setDate(ad.getTime());
				ob.setPV(ad.getPv() + "");
				ob.setUV(ad.getUv() + "");
				ob.setId(vo.getId());
				ob.setName(vo.getName());
				ob.setTotal(vo.getTotal());
				ob.setUrl(ad.getUrl());
				ob.setUnitPrice(vo.getUnitPrice());
				if (ob.getAddMoney() == "" || ob.getAddMoney() == null)
					ob.setAddMoney("无");
				ob.setBalance(vo.getBalance() + last - (pv + last_pv) * vo.getUnitPrice());
				returnList.add(ob);

			}
		} catch (AppException e) {
			e.printStackTrace();
		}
		Collections.reverse(returnList);// 倒序
		pageResponse.setITotalRecords(returnList.size());
		pageResponse.setITotalDisplayRecords(returnList.size());
		return returnList;
	}

	/**
	 * 增加广告商 spread_advertising
	 * 
	 */
	@Override
	public int add(AdvertisingModel model) {
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(AdvertisingVO.class);
		AdvertisingVO entity = new AdvertisingVO();
		entity.setBalance(model.getBalance());
		try {
			entity.setDate(dateformat.parse(model.getDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (model.getDate() == null || model.getDate().length() == 0) {
			entity.setDate(new Date());
		} else {
			try {
				entity.setDate(dateformat.parse(model.getDate()));
			} catch (ParseException e) {
				System.err.println("日期" + model.getDate() + "解析异常" + e);
				e.printStackTrace();
			}
		}
		entity.setName(model.getName());
		entity.setTotal(model.getTotal());
		entity.setUnitPrice(model.getUnitPrice());
		entity.setUrl(model.getUrl());
		entity.setUserid(model.getUserid());
		Object object = dao.save(entity);
		if (object == null) {
			return 0;
		} else {
			return 1;
		}
	}

}
